package com.blockmeta.bbs.businesslibrary.base;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.PowerManager;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.blankj.utilcode.util.LogUtils;
import com.blockmeta.bbs.baselibrary.utils.SharedPreferenceUtil;
import com.blockmeta.bbs.baselibrary.utils.StatusBarUtils;
import com.blockmeta.bbs.baselibrary.utils.richtext.RichText;
import com.blockmeta.bbs.businesslibrary.BaseBussinessApp;
import com.blockmeta.bbs.businesslibrary.R;
import com.blockmeta.bbs.businesslibrary.arouter.RouterHelper;
import com.blockmeta.bbs.businesslibrary.arouter.RouterPath;
import com.blockmeta.bbs.businesslibrary.business.UmengEvent;
import com.blockmeta.bbs.businesslibrary.constant.Constant;
import com.blockmeta.bbs.businesslibrary.constant.NetConstant;
import com.blockmeta.bbs.businesslibrary.eventbus.MsgSuccess;
import com.blockmeta.bbs.businesslibrary.launch.SplashActivity;
import com.blockmeta.bbs.businesslibrary.popwindow.TopPopupWindow;
import com.blockmeta.bbs.businesslibrary.util.AccountHelper;

import com.hellobike.flutter.thrio.navigator.ThrioNavigator;
import com.trello.rxlifecycle2.components.support.RxAppCompatActivity;
import com.umeng.analytics.MobclickAgent;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.devio.takephoto.app.TakePhoto;
import org.devio.takephoto.app.TakePhotoImpl;
import org.devio.takephoto.model.InvokeParam;
import org.devio.takephoto.model.TContextWrap;
import org.devio.takephoto.model.TResult;
import org.devio.takephoto.permission.InvokeListener;
import org.devio.takephoto.permission.PermissionManager;
import org.devio.takephoto.permission.TakePhotoInvocationHandler;
import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import butterknife.ButterKnife;
import butterknife.Unbinder;
import okhttp3.Call;

/**
 * Created by author on 2017/12/26.
 */

public abstract class BaseActivity extends RxAppCompatActivity implements TakePhoto.TakeResultListener, InvokeListener {
    private ImageView base_back;
    private TextView base_title;
    private LinearLayout base_root;
    public RelativeLayout rl_tiltle;
    private TextView center_tv;
    private ImageView center_iv;
    private FrameLayout ll_content;
    private LinearLayout left_iv;
    private View base_view;
    private Window window;
    private PowerManager.WakeLock mWakeLock;//保持屏幕常亮
    public TakePhoto takePhoto;//图片选择框架
    private InvokeParam invokeParam;//图片选择
    public Unbinder mUnbinder;
    private LinearLayout right_click;
    private ImageView right_iv;
    protected long mOnCreateMillion;
    public Context mContext;
    private TextView right_tv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;
        LogUtils.i("activityname" + this.getClass().getName());
        restartAppIfBeKilled();

        ARouter.getInstance().inject(mContext);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            android.webkit.WebView.enableSlowWholeDocumentDraw();
        }
        initSerilization();
        setContentView(R.layout.activity_base);
        setStatusBarColor();
        initOrgView();
        mOnCreateMillion = System.currentTimeMillis();
    }

    private void restartAppIfBeKilled() {
        if(this.getClass() == SplashActivity.class){
            return;
        }
        switch (BaseBussinessApp.getApp().getAppStatus()) {
            case BaseBussinessApp.STATUS_FORCE_KILLED:
                restartApp();
                break;
            case BaseBussinessApp.STATUS_NORMAL:
            default:
                break;
        }
    }

    private void restartApp() {
        //当系统被回收重建时,重启app初始化,避免行情和im等服务发生初始化异常
        Intent intent = new Intent(this, SplashActivity.class);
        startActivity(intent);
        finish();
    }

    /**设置状态栏的颜色，特殊的页面可以重写*/
    public void setStatusBarColor() {
        StatusBarUtils.fitSystemWindows(this,true);
        if (SharedPreferenceUtil.getBoolean(mContext, Constant.Night_Mode, false)) {
            StatusBarUtils.setWindowStatusBarColor(this, R.color.status_red_night);
            StatusBarUtils.setDarkMode(this);
        } else {
            StatusBarUtils.setWindowStatusBarColor(this, R.color.chainthing_status_color);
            StatusBarUtils.setLightMode(this);
        }
    }

    //序列化数据
    public void initSerilization() {

    }


    private void initOrgView() {
        //标题
        rl_tiltle = findViewById(R.id.rl_title);
        base_root = findViewById(R.id.base_root);
        //文字图片
        center_tv = findViewById(R.id.center_tv);
        //文字图片
        center_iv = findViewById(R.id.center_iv);
        ll_content = findViewById(R.id.ll_content);
        //返回
        left_iv = findViewById(R.id.left_iv);
        left_iv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                setLeftIvOnListener();
            }
        });
        //遮盖层
        base_view = findViewById(R.id.base_view);
        if (showTitle()) {
            rl_tiltle.setVisibility(View.VISIBLE);
        } else {
            rl_tiltle.setVisibility(View.GONE);
        }
        //右边的图标以及点击
        right_click = (LinearLayout) findViewById(R.id.right_click);
        right_iv = (ImageView) findViewById(R.id.right_iv);
        right_tv = (TextView) findViewById(R.id.right_tv);
        right_click.setVisibility(showRight() ? View.VISIBLE : View.GONE);
        if(!TextUtils.isEmpty(showRightText())){
            right_iv.setVisibility(View.GONE);
            right_tv.setVisibility(View.VISIBLE);
            right_tv.setText(showRightText());
        }else if (showRightImg() != 0) {
            right_iv.setImageResource(showRightImg());
        }
        ll_content.addView(setView());
        right_click.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                toDoRightSomething();
            }


        });
        mUnbinder = ButterKnife.bind(this);


        initialize();
    }


    public boolean showRight() {
        return false;
    }

    public String showRightText() {
        return "";
    }

    public int showRightImg() {
        return 0;
    }

    public void toDoRightSomething() {
    }

    protected void initialize() {
        //如果使用butterknife请使用此方法来做初始化或者在onStart()方法中

    }

    public void setTitleText(String title) {
        if (title == null) {
            return;
        }
        center_tv.setText(title);
    }


    protected abstract boolean showTitle();

    public void setLeftIvOnListener() {
        ThrioNavigator.pop();
//        finish();
    }

    public abstract View setView();

    public void activityStartActivity(Context context, Class cls) {
        Intent intent = new Intent(context, cls);
        startActivity(intent);
    }

    public void activityStartActivity(Context context, Class cls, String key, String value) {
        Intent intent = new Intent(context, cls);
        intent.putExtra(key, value);
        startActivity(intent);
    }

    public void activityStartActivity(Context context, Class cls, String key1, String value1, String key2, String value2) {
        Intent intent = new Intent(context, cls);
        intent.putExtra(key1, value1);
        intent.putExtra(key2, value2);
        startActivity(intent);
    }


    @SuppressLint("WakelockTimeout")
    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
        //是否保持屏幕常亮
        Boolean isKeepScreenOn = SharedPreferenceUtil.getBoolean(this, Constant.KEEP_SCREEN_ON, false);
        mWakeLock = ((PowerManager) getSystemService(POWER_SERVICE))
                            .newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK
                                                 | PowerManager.ON_AFTER_RELEASE, "sss:PowerManager");
        if (isKeepScreenOn) mWakeLock.acquire();
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
        if (mWakeLock.isHeld()) mWakeLock.release();
//        DialogUtil.detach();
//        SharedUtils.detach();
    }

    @Override
    protected void onDestroy() {
        RichText.clear(this);
        super.onDestroy();
        if(mUnbinder != null){
            mUnbinder.unbind();
            mUnbinder=null;
        }
    }

    //--------------------------------------------takePhoto----------------------------------------------
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        getTakePhoto().onSaveInstanceState(outState);
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        getTakePhoto().onActivityResult(requestCode, resultCode, data);
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.TPermissionType type = PermissionManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.handlePermissionsResult(this, type, invokeParam, this);
    }

    /**
     * 获取TakePhoto实例
     *
     * @return
     */
    public TakePhoto getTakePhoto() {
        if (takePhoto == null) {
            takePhoto = (TakePhoto) TakePhotoInvocationHandler.of(this).bind(new TakePhotoImpl(this, this));
        }
        return takePhoto;
    }

    @Override
    public void takeSuccess(TResult result) {
    }

    @Override
    public void takeFail(TResult result, String msg) {
    }


    @Override
    public void takeCancel() {
    }

    @Override
    public PermissionManager.TPermissionType invoke(InvokeParam invokeParam) {
        PermissionManager.TPermissionType type = PermissionManager.checkPermission(TContextWrap.of(this), invokeParam.getMethod());
        if (PermissionManager.TPermissionType.WAIT.equals(type)) {
            this.invokeParam = invokeParam;
        }
        return type;
    }

    //点击空白区域 自动隐藏软键盘
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (null != this.getCurrentFocus()) {
            /**
             * 点击空白位置 隐藏软键盘
             */
            InputMethodManager mInputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);

            return mInputMethodManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), 0);
        }
        return super.onTouchEvent(event);
    }

    /**
     * 在此校验任务中心的任务是否完成，完成则弹出提示框
     * @param view 提示框在该view下显示
     *1-邀请好友注册 2-参与活动报名 3-分享快讯/资讯/币种F10 4-发表帖子 5-阅读资讯/学院板块文章 6-发表快讯利好利空观点 7-发表评论 8-修改头像 9-修改昵称 10-手机认证 11-绑定微信/QQ/微博 12-给个好评 13-兑换 14-悬赏 15-打赏 16-回帖奖励 17-主题付费
     */
    public void isTaskComplete(int taskType, final View view){
        OkHttpUtils.post()
                .addHeader("token", SharedPreferenceUtil.getString(this, Constant.TOKEN,null))
                .addHeader("uid", AccountHelper.getUid())
                .url(String.format(Locale.CHINESE,NetConstant.TASK_COMPLETE,taskType))
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(String response, int id) {
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            int coins = jsonObject.getInt("award");
                            if (coins==0) {
                                return;
                            }
                            showPop(coins, view);
                            EventBus.getDefault().postSticky(new MsgSuccess(Constant.UPDATE_COINS));
                            UmengEvent.eventStatistics(BaseActivity.this,Constant.U_MINE_task_snackbar,null);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }
    public void isTaskComplete(final View view,int tid){
        OkHttpUtils.post()
                .addHeader("token", SharedPreferenceUtil.getString(this, Constant.TOKEN,null))
                .addHeader("uid", AccountHelper.getUid())
                .url(String.format(Locale.CHINESE, NetConstant.TASK_COMPLETE,4)+"?tid="+tid)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(String response, int id) {
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            int coins = jsonObject.getInt("award");
                            if (coins==0) {
                                return;
                            }
                            showPop(coins, view);
                            UmengEvent.eventStatistics(BaseActivity.this, Constant.U_MINE_task_snackbar,null);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }
    public void isTaskCompleteNoHint(int taskType){
            OkHttpUtils.post()
                    .addHeader("token", SharedPreferenceUtil.getString(this, Constant.TOKEN,null))
                    .addHeader("uid", AccountHelper.getUid())
                    .url(String.format(Locale.CHINESE,NetConstant.TASK_COMPLETE,taskType))
                    .build()
                    .execute(new StringCallback() {
                        @Override
                        public void onError(Call call, Exception e, int id) {

                        }

                        @Override
                        public void onResponse(String response, int id) {

                        }
                    });
        }

    public void showPop(int coins,View view) {
        TopPopupWindow topPopupWindow = new TopPopupWindow(BaseActivity.this);
        topPopupWindow.mCoinCount.setText(String.format(Locale.CHINESE,"%d金币", coins));
        if (view == null){
            topPopupWindow.showPopupWindow(rl_tiltle);
        }else {
            topPopupWindow.showPopupWindow(view);
        }
    }

    public void startActivityToViewPager(Context context, List<String> pics, int position) {

        RouterHelper.buildPath(RouterPath.VIEWPAGER_ACTIVITY)
                .withStringArrayList(Constant.ZERO,new ArrayList<>(pics))
                .withInt(Constant.ONE,position)
                .navigation(context);
    }

    /**
     * 跳到登陆页面
     *
     * @param context
     */
    public void startActivityToLogin(Context context) {
        RouterHelper.startActivity(context,RouterPath.PHONE_LOGIN_ACTIVITY);
    }

    public void startActivityToBindPhone(Context context) {
        RouterHelper.startActivity(context,RouterPath.BIND_ACCOUNT_PHONE_ACTIVITY);
    }

    /**
     * 校验登陆态，未登录跳转登陆页面
     * @return true表示登陆
     */
    public boolean checkLoginStatus(){
        boolean isLogin = AccountHelper.isLogin();
        if (!isLogin){
            RouterHelper.startActivity(mContext,RouterPath.ACCOUNT_LOGIN_ACTIVITY);
        }
        return isLogin;
    }
}
